package com.bhs.sansong.ui.shipments;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.ArrayMap;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bhs.sansong.R;
import com.bhs.sansong.adapter.LogisticsModeAdapter;
import com.bhs.sansong.base.BaseActivity;
import com.bhs.sansong.base.BaseBean;
import com.bhs.sansong.bean.AddressInfo;
import com.bhs.sansong.bean.AddressList;
import com.bhs.sansong.bean.AdvancePayment;
import com.bhs.sansong.bean.CompanyInfo;
import com.bhs.sansong.bean.CompanyInformation;
import com.bhs.sansong.bean.CouponSearchBean;
import com.bhs.sansong.bean.FeeDetail;
import com.bhs.sansong.bean.LogisticsMode;
import com.bhs.sansong.bean.OrderCreationSuccess;
import com.bhs.sansong.bean.OrderDetailsBean;
import com.bhs.sansong.bean.Outlets;
import com.bhs.sansong.bean.OutletsData;
import com.bhs.sansong.bean.PlatformPriceBean;
import com.bhs.sansong.bean.TimeBean;
import com.bhs.sansong.ui.dialog.BottomCouponDialog;
import com.bhs.sansong.ui.dialog.GoodTypeDialog;
import com.bhs.sansong.ui.dialog.MyClickListener2;
import com.bhs.sansong.ui.dialog.OutletsDialog;
import com.bhs.sansong.ui.dialog.PackagingDialog;
import com.bhs.sansong.ui.dialog.PaymentDetailsPopWindows;
import com.bhs.sansong.ui.dialog.PriceInputDialog;
import com.bhs.sansong.net.Config;
import com.bhs.sansong.net.NetCallBack;
import com.bhs.sansong.ui.findLogistics.LogisticsCompaniesListActivity;
import com.bhs.sansong.ui.other.WebViewActivity;
import com.bhs.sansong.ui.wallet.PayDeskActivity;
import com.bhs.sansong.utils.DateUtils;
import com.bhs.sansong.utils.LogUtils;
import com.bhs.sansong.utils.MyUtils;
import com.bhs.sansong.utils.ToastUtil;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.enums.PopupPosition;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 发布新订单
 */
public class IssueNewOrderActivity extends BaseActivity implements NetCallBack, View.OnClickListener, RadioGroup.OnCheckedChangeListener {

    private TextView mTvDepartureAddress;
    private TextView mTvDepartureInfo;
    private TextView mTvDeliveryAddress;
    private TextView mTvDeliveryInfo;
    private TextView mTvGoodType;
    private TextView mTvPackaging;
    private RadioButton mRbZisongzhuanxian;
    private RadioButton mRbShangmengtihuo;
    private RadioButton mSonghuoshangmeng;
    private RadioButton mRbZiti;
    private LinearLayout mLlSelectCompany;
    private ImageView mIvCompanyDoorPicture;
    private TextView mTvCompanyName;
    private TextView mTvCompanyAddress;
    private RadioGroup mRgReceiptSlip;
    private RadioButton mRbDispenseWith;
    private RadioButton mRbReceipt;
    private RadioButton mRbAcknowledgement;
    private EditText mEtRemark;
    private RecyclerView mRvLogisticsMode;
    private CheckBox mCbAgreement;
    private TextView mTvPredict;//预计
    private TextView mTvPredictMoney;
    private View mView;
    private TextView mTvPayType;
    private TextView mTvHint;
    private TextView mTvConfirm;
    private AddressInfo shipAddress, shippingAddress;
    private String orderType;
    private AddressList bean;
    private LogisticsModeAdapter logisticsModeAdapter;
    private List<LogisticsMode> modeList = new ArrayList<>();
    private ConstraintLayout mClBottom;
    private RadioButton mRbBilling;
    private String outlets_id;
    private String receipt_type = "1";
    private RadioGroup mRgJiaohuofangshi;
    private RadioGroup mRgPeisongfangshi;
    private int index = 0;
    private String appointmentTime;
    private BigDecimal lastMoney=new BigDecimal("0");//最终价格
    private BigDecimal freight=new BigDecimal("0");//选择价格
    private BigDecimal discountCouponMoney=new BigDecimal("0");//优惠券
    private BigDecimal redEnvelopePrice=new BigDecimal("0");//红包
    private ActivityResultLauncher<Intent> intentActivityResultLauncher;
    private LinearLayout mLlSelfPickingDot;
    private TextView mTvWebsite;
    private CompanyInformation companyInfo;//公司信息
    private List<Outlets> outletsList;
    private OutletsDialog outletsDialog;
    private String deliver_sn;
    private TextView mTvTitle;
    private LinearLayout mLlAppointment;
    private TextView mTvAppointment;
    private String displayTime;
    private String uploadTime;
    private String placeOrderType;//找物流进来的 不用选公司
    private RadioButton mRbDiscountCoupon;
    private RadioButton mRbRedPacket;
    private TextView mTvDiscountType;
    private TextView mTvDiscountPrice;
    private RadioGroup mRgDiscountType;
    private LinearLayout mLlLogisticsMode;
    private LinearLayout mLlSelectOffer;
    private LinearLayout mLlPreferentialPrice;
    private String deliveryExpense, pickUpCharge;//送货费 提货费
    private String networkCity;
    private String pay_method = "1";//支付方式

    @Override
    public int initLayout() {
        return R.layout.activity_issue_new_order;
    }

    @Override
    public void initView() {
        networkCity = getIntent().getStringExtra("networkCity");
        placeOrderType = getIntent().getStringExtra("place_order_type");
        companyInfo = getIntent().getParcelableExtra("companyInfo");
        appointmentTime = getIntent().getStringExtra("appointmentTime");
        shipAddress = getIntent().getParcelableExtra("shipAddress");
        shippingAddress = getIntent().getParcelableExtra("shippingAddress");
        orderType = getIntent().getStringExtra("order_type");
        deliver_sn = getIntent().getStringExtra("deliver_sn");
        displayTime = getIntent().getStringExtra("displayTime");
        uploadTime = getIntent().getStringExtra("uploadTime");
        mTvTitle = findViewById(R.id.tv_title);
        mTvDepartureAddress = findViewById(R.id.tv_departure_address);
        mTvDepartureInfo = findViewById(R.id.tv_departure_info);
        findViewById(R.id.tv_shipments_address_book).setOnClickListener(this);
        findViewById(R.id.fl_exchange).setOnClickListener(this);
        mTvDeliveryAddress = findViewById(R.id.tv_delivery_address);
        mTvDeliveryAddress.setOnClickListener(this);
        mTvDeliveryInfo = findViewById(R.id.tv_delivery_info);
        findViewById(R.id.tv_receive_address_book).setOnClickListener(this);
        mTvGoodType = findViewById(R.id.tv_good_type);
        mTvGoodType.setOnClickListener(this);
        mTvPackaging = findViewById(R.id.tv_packaging);
        mTvPackaging.setOnClickListener(this);
        mRbZisongzhuanxian = findViewById(R.id.rb_zisongzhuanxian);
        mRbShangmengtihuo = findViewById(R.id.rb_shangmengtihuo);
        mSonghuoshangmeng = findViewById(R.id.songhuoshangmeng);
        mRbZiti = findViewById(R.id.rb_ziti);
        mLlSelectCompany = findViewById(R.id.ll_select_company);
        mIvCompanyDoorPicture = findViewById(R.id.iv_company_door_picture);
        mTvCompanyName = findViewById(R.id.tv_company_name);
        mTvCompanyAddress = findViewById(R.id.tv_company_address);
        mRgReceiptSlip = findViewById(R.id.rg_receipt_slip);
        mRbDispenseWith = findViewById(R.id.rb_dispense_with);
        mRbReceipt = findViewById(R.id.rb_receipt);
        mRbAcknowledgement = findViewById(R.id.rb_acknowledgement);
        mEtRemark = findViewById(R.id.et_remark);
        mRvLogisticsMode = findViewById(R.id.rv_logistics_mode);
        mCbAgreement = findViewById(R.id.cb_agreement);
        mTvPredict = findViewById(R.id.tv_predict);
        mTvPredictMoney = findViewById(R.id.tv_predict_money);
        mView = findViewById(R.id.view);
        mTvPayType = findViewById(R.id.tv_pay_type);
        mTvPayType.setOnClickListener(this);
        mTvHint = findViewById(R.id.tv_hint);
        mTvConfirm = findViewById(R.id.tv_confirm);
        mClBottom = findViewById(R.id.cl_bottom);
        mTvConfirm.setOnClickListener(this);
        mRbBilling = findViewById(R.id.rb_billing);
        mRgJiaohuofangshi = findViewById(R.id.rg_jiaohuofangshi);
        mRgPeisongfangshi = findViewById(R.id.rg_peisongfangshi);
        mLlSelfPickingDot = findViewById(R.id.ll_Self_picking_dot);
        mLlSelfPickingDot.setOnClickListener(this);
        mTvWebsite = findViewById(R.id.tv_website);
        mLlAppointment = findViewById(R.id.ll_appointment);
        mLlAppointment.setOnClickListener(this);
        mTvAppointment = findViewById(R.id.tv_appointment);

        mRbDiscountCoupon = findViewById(R.id.rb_discount_coupon);
        mRbRedPacket = findViewById(R.id.rb_red_packet);
        mTvDiscountType = findViewById(R.id.tv_discount_type);
        mTvDiscountPrice = findViewById(R.id.tv_discount_price);
        mRbDiscountCoupon.setChecked(true);
        mRgDiscountType = findViewById(R.id.rg_discount_type);
        mLlLogisticsMode = findViewById(R.id.ll_logistics_mode);
        mLlSelectOffer = findViewById(R.id.ll_select_offer);
        mLlPreferentialPrice = findViewById(R.id.ll_preferential_price);
        findViewById(R.id.ll_receive).setOnClickListener(this);
        findViewById(R.id.ll_send).setOnClickListener(this);
    }

    private void initialization() {
        if (!TextUtils.isEmpty(appointmentTime) || !TextUtils.isEmpty(uploadTime)) {
            mLlAppointment.setVisibility(View.VISIBLE);
            mTvAppointment.setText(displayTime);
        }
        if (shipAddress != null) {
            setShipAddress();
            setShippingAddress();
        }
        mTvTitle.setText(orderType.equals("1") ? "指派发货" : "极速发货");
        if (orderType.equals("1")) {
            mLlSelectCompany.setVisibility(View.VISIBLE);
            mLlSelfPickingDot.setVisibility(View.VISIBLE);
            mLlSelectCompany.setOnClickListener(this);
            mLlSelfPickingDot.setOnClickListener(this);
            outletsDialog = new OutletsDialog(mContext);
            outletsDialog.setMyClickListener(new MyClickListener2() {
                @Override
                public void onClick(String id, String info) {
                    outlets_id = id;
                    mTvWebsite.setText(info);
                }
            });
        }
    }

    private void callBack() {
        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                //此处是跳转的result回调方法
                if (result.getData() != null) {
                    if (result.getResultCode() == 1) {
                        shipAddress = result.getData().getParcelableExtra("info");
                        if (companyInfo != null) {
                            if (shipAddress.getCity().equals(companyInfo.getStartCity())) {
                                setShipAddress();
                                platformPrice();
                            } else {
                                ToastUtil.show("地址与专线不匹配");
                            }
                        } else {
                            setShipAddress();
                            platformPrice();
                        }
                    } else if (result.getResultCode() == 2) {
                        shippingAddress = result.getData().getParcelableExtra("info");
                        if (companyInfo != null) {
                            if (shippingAddress.getCity().equals(companyInfo.getEndCity())) {
                                setShippingAddress();
                                platformPrice();
                            } else {
                                ToastUtil.show("地址与专线不匹配");
                            }
                        } else {
                            setShippingAddress();
                            platformPrice();
                        }
                    } else if (result.getResultCode() == 3) {
                        String logistics_id = "";
                        if (companyInfo != null) {
                            logistics_id = companyInfo.getLogistics_id();
                        }

                        companyInfo = result.getData().getParcelableExtra("info");

                        //选择相同的公司无需在设置值
                        if (logistics_id.equals(companyInfo.getLogistics_id())) {
                            return;
                        }
                        setCompanyInfo();

                    }

                }
            }
        });
    }

    private void setCompanyInfo() {
        if (companyInfo == null) {
            return;
        }
        mTvCompanyName.setText(companyInfo.getCompany_name());
        mTvCompanyAddress.setText(companyInfo.getAddress());
        mTvCompanyAddress.setVisibility(View.VISIBLE);
        Glide.with(mActivity).load(companyInfo.getCompany_pic()).into(mIvCompanyDoorPicture);
        getLogisticsCompanyOutlets();
    }

    private void getLogisticsCompanyOutlets() {
        if (shippingAddress == null && TextUtils.isEmpty(networkCity)) {
            return;
        }
        Map<String, String> map = new ArrayMap<>();
        map.put("logistics_id", companyInfo.getLogistics_id());
        if (shippingAddress != null) {
            map.put("city", shippingAddress.getCity());
        } else {
            map.put("city", networkCity);
        }
        map.put("page", "1");
        map.put("limit", "100");
        networkRequest(netApi.get_logistics_company_outlets(map), this, 999);
    }


    @Override
    public void initData() {
        setCompanyInfo();
        callBack();
        //再来一单获取订单详情
        if (!TextUtils.isEmpty(deliver_sn)) {
            networkRequest(netApi.getOrderDetails(deliver_sn), this, 9528);
        } else {
            initialization();
        }
        mRbDispenseWith.setChecked(true);
        mRbZisongzhuanxian.setChecked(true);
        mRbZiti.setChecked(true);
        networkRequest(netApi.get_order_common_data(), this, 9527);
        logisticsModeAdapter = new LogisticsModeAdapter(modeList, mActivity);
        mRvLogisticsMode.setAdapter(logisticsModeAdapter);
        mRvLogisticsMode.setLayoutManager(new LinearLayoutManager(mActivity, RecyclerView.HORIZONTAL, false));

        logisticsModeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (position != index) {
                    modeList.get(index).setCheck(false);
                    modeList.get(position).setCheck(true);
                    index = position;
                    freight = new BigDecimal(modeList.get(position).getPrice());
                    if (mRbDiscountCoupon.isChecked()) {
                        lastMoney = freight.subtract(discountCouponMoney);
                    } else {
                        lastMoney = freight.subtract(redEnvelopePrice);
                    }
                    mTvPredictMoney.setText(String.format("%s元", lastMoney));
                }
                //议价弹出输入法
                if (modeList.get(position).getMode() == 3) {
                    priceInputDialog();
                } else {
                    getDiscounts();
                }
                logisticsModeAdapter.notifyDataSetChanged();
                isDiscount();
            }
        });
        String str = "我已阅读并同意《货物运输协议》";

        SpannableStringBuilder spannableBuilder = new SpannableStringBuilder(str);
        // 在设置点击事件、同时设置字体颜色
        ClickableSpan clickableSpanOne = new ClickableSpan() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(mActivity, WebViewActivity.class)
                        .putExtra("url", Config.getTransportationUrl())
                        .putExtra("title", "货物运输协议"));
            }

            @Override
            public void updateDrawState(TextPaint paint) {
                paint.setColor(Color.parseColor("#485EF4"));
                // 设置下划线 true显示、false不显示
                paint.setUnderlineText(false);
            }
        };
        spannableBuilder.setSpan(clickableSpanOne, 7, 15, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mCbAgreement.setMovementMethod(LinkMovementMethod.getInstance());
        mCbAgreement.setText(spannableBuilder);
        mRgReceiptSlip.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (i == R.id.rb_dispense_with) {
                    receipt_type = "1";
                } else if (i == R.id.rb_receipt) {
                    receipt_type = "2";
                } else if (i == R.id.rb_acknowledgement) {
                    receipt_type = "3";
                }
            }
        });
        mRgPeisongfangshi.setOnCheckedChangeListener(this);
        mRgJiaohuofangshi.setOnCheckedChangeListener(this);

        mRgDiscountType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (i == R.id.rb_discount_coupon) {
                    mTvDiscountType.setText("优惠券");
                    if (discountCouponMoney.compareTo(new BigDecimal("0")) > 0) {
                        mTvDiscountPrice.setText(String.format("可抵扣金额：%s元", discountCouponMoney));
                        lastMoney = freight.subtract(discountCouponMoney);
                        mTvPredictMoney.setText(String.format("%s元", lastMoney));
                    } else {
                        if (couponSearchBean != null) {
                            mTvDiscountPrice.setText(String.format("你有%s张可用的优惠券", couponSearchBean.getData().getList().size()));
                        }
                    }
                } else if (i == R.id.rb_red_packet) {
                    mTvDiscountType.setText("红包");
                    mTvDiscountPrice.setText(String.format("可抵扣金额：%s元", redEnvelopePrice));
                    lastMoney = freight.subtract(redEnvelopePrice);
                    mTvPredictMoney.setText(String.format("%s元", lastMoney));
                }
            }
        });
    }

    private void platformPrice() {
        if (shipAddress == null || shippingAddress == null || goodTypeDialog == null) {
            return;
        }
        Map<String, String> map = new ArrayMap<>();
        map.put("start_city", shipAddress.getCity());
        map.put("end_city", shippingAddress.getCity());
        map.put("goods_weight", String.valueOf(goodTypeDialog.getWeight()));
        map.put("goods_volume", String.valueOf(goodTypeDialog.getVolume()));
        map.put("jiaohuo_type", mRbZisongzhuanxian.isChecked() ? "1" : "2");
        map.put("peisong_type", mSonghuoshangmeng.isChecked() ? "1" : "2");
        if (companyInfo != null) {
            map.put("logistics_id", companyInfo.getLogistics_id());
            map.put("line_id", companyInfo.getLine_id());
        }
        networkRequest(netApi.get_platform_price(map), this, 888);
    }

    PriceInputDialog dialog;

    private void priceInputDialog() {
        if (dialog == null) {
            dialog = new PriceInputDialog(mActivity, modeList.get(0).getPrice());
            dialog.setMyClickListener(new MyClickListener2() {
                @SuppressLint("NotifyDataSetChanged")
                @Override
                public void onClick(String id, String info) {
                    modeList.get(2).setPrice(info);
                    logisticsModeAdapter.notifyDataSetChanged();
                    freight = new BigDecimal(info);
                    if (mRbDiscountCoupon.isChecked()) {
                        lastMoney = freight.subtract(discountCouponMoney);
                    } else {
                        lastMoney = freight.subtract(redEnvelopePrice);
                    }
                    mTvPredictMoney.setText(String.format("%s元", lastMoney));
                }
            });
        }
        new XPopup.Builder(mActivity)
                .autoOpenSoftInput(true)
                .asCustom(dialog)
                .show();
    }

    private GoodTypeDialog goodTypeDialog;
    private PackagingDialog packagingDialog;
    private PaymentDetailsPopWindows popWindows;
    private BasePopupView xPopup;

    private String mode;

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_good_type:
                if (bean == null) {
                    ToastUtil.show("正在获取数据");
                    return;
                }
                if (goodTypeDialog == null) {
                    goodTypeDialog = new GoodTypeDialog(mActivity);
                }
                if (goodTypeDialog.getData() == null) {
                    goodTypeDialog.setData(bean.getData().getGoods_type());
                    goodTypeDialog.setMyClickListener(new MyClickListener2() {
                        @SuppressLint("NotifyDataSetChanged")
                        @Override
                        public void onClick(String id, String info) {
                            mTvGoodType.setText(info);
                            platformPrice();
                            mode = id;
                        }
                    });
                }
                goodTypeDialog.show();
                break;
            case R.id.tv_packaging:
                if (bean == null) {
                    ToastUtil.show("正在获取数据");
                    return;
                }
                if (packagingDialog == null) {
                    packagingDialog = new PackagingDialog(mActivity);
                }
                if (packagingDialog.getData() == null) {
                    packagingDialog.setData(bean.getData().getPackup_type());
                    packagingDialog.setMyClickListener(new MyClickListener2() {
                        @Override
                        public void onClick(String id, String info) {
                            mTvPackaging.setText(info);
                        }
                    });
                }
                packagingDialog.show();
                break;
            case R.id.tv_pay_type:
                if (popWindows == null) {
                    popWindows = new PaymentDetailsPopWindows(mActivity, Gravity.START);
                    xPopup = new XPopup.Builder(mActivity)
                            .atView(mClBottom)
                            .isViewMode(true)
                            .popupPosition(PopupPosition.Top)
                            .asCustom(popWindows);
                    popWindows.setMyClickListener(new MyClickListener2() {
                        @Override
                        public void onClick(String id, String info) {
                            pay_method = id;
                            if(pay_method.equals("1")) {
                                mTvPayType.setText("现付.明细");
                            }else {
                                mTvPayType.setText("到付.明细");
                            }
                            isDiscount();
                        }
                    });
                }
                xPopup.show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        List<FeeDetail> mList = new ArrayList<>();
                        BigDecimal carriage = freight;
                        if (mRbShangmengtihuo.isChecked()) {
                            carriage = carriage.subtract(new BigDecimal(pickUpCharge));
                        }
                        if (mSonghuoshangmeng.isChecked()) {
                            carriage = carriage.subtract(new BigDecimal(deliveryExpense));
                        }
                        mList.add(new FeeDetail("运费", carriage.toString()));

                        if (mRbShangmengtihuo.isChecked()) {
                            mList.add(new FeeDetail("提货费", pickUpCharge));
                        }
                        if (mSonghuoshangmeng.isChecked()) {
                            mList.add(new FeeDetail("送货费", deliveryExpense));
                        }
                        if (mRbDiscountCoupon.isChecked() && !TextUtils.isEmpty(coupon_id)) {
                            mList.add(new FeeDetail("优惠券", "-" + discountCouponMoney.toString()));
                        }
                        if (mRbRedPacket.isChecked()) {
                            mList.add(new FeeDetail("红包", "-" + redEnvelopePrice.toString()));
                        }
                        popWindows.mAdapter.setNewData(mList);
                        popWindows.mTvEstimatedCost.setText(String.format("%s元", lastMoney.toString()));
                    }
                }, 300);

                break;
            case R.id.tv_confirm:
                confirm();
                break;
            case R.id.fl_exchange:
                AddressInfo temp = shipAddress;
                shipAddress = shippingAddress;
                shippingAddress = temp;
                setShipAddress();
                setShippingAddress();
                break;
            case R.id.tv_shipments_address_book:
            case R.id.ll_send:
                Intent intent3 = new Intent(mActivity, CompleteAddressActivity.class);
                intent3.putExtra("type", 1);
                intentActivityResultLauncher.launch(intent3);
                break;
            case R.id.tv_receive_address_book:
            case R.id.ll_receive:
                Intent intent4 = new Intent(mActivity, CompleteAddressActivity.class);
                intent4.putExtra("type", 2);
                intentActivityResultLauncher.launch(intent4);
                break;
            case R.id.ll_select_company:
                if (placeOrderType == null || !placeOrderType.equals("1")) {
                    if (shipAddress != null) {
                        intentActivityResultLauncher.launch(new Intent(mActivity, LogisticsCompaniesListActivity.class)
                                .putExtra("startCity", shipAddress.getCity())
                                .putExtra("endCity", shippingAddress.getCity())
                                .putExtra("type", 1));
                    } else {
                        intentActivityResultLauncher.launch(new Intent(mActivity, LogisticsCompaniesListActivity.class)
                                .putExtra("type", 1));
                    }
                }
                break;
            case R.id.ll_Self_picking_dot:
                outletsDialog.show();
                break;
            case R.id.ll_appointment:
                //条件选择器
                if (pvOptions == null) {
                    getTimeData();
                    pvOptions = new OptionsPickerBuilder(mActivity, new OnOptionsSelectListener() {
                        @Override
                        public void onOptionsSelect(int options1, int option2, int options3, View v) {
                            //上传给接口的时间
                            uploadTime = list1.get(options1).getFormattingTime()
                                    + " " + list2.get(options1).get(option2).getTime()
                                    + ":" + list3.get(options1).get(option2).get(options3).getTime();
                            //显示时间
                            displayTime = list1.get(options1).getPickerViewText()
                                    + " " + list2.get(options1).get(option2).getTime()
                                    + ":" + list3.get(options1).get(option2).get(options3).getTime();
                            LogUtils.d(uploadTime + "==" + displayTime);

                        }
                    }).build();
                    pvOptions.setPicker(list1, list2, list3);
                }
                pvOptions.show();
                break;
            case R.id.ll_preferential_price:
                if (mRbDiscountCoupon.isChecked()) {
                    preferentialPrice();
                }
                break;
        }
    }

    private void isDiscount() {
        if (pay_method.equals("1") && index != 3) {
            mLlSelectOffer.setVisibility(View.VISIBLE);
            mLlPreferentialPrice.setVisibility(View.VISIBLE);
        } else {
            mLlSelectOffer.setVisibility(View.GONE);
            mLlPreferentialPrice.setVisibility(View.GONE);
        }
    }

    private BottomCouponDialog couponDialog;
    private String coupon_id;

    private void preferentialPrice() {
        couponDialog = new BottomCouponDialog(this, couponSearchBean.getData().getList());
        couponDialog.show();
        couponDialog.setMyClickListener(new MyClickListener2() {
            @Override
            public void onClick(String id, String info) {
                coupon_id = id;
                discountCouponMoney = new BigDecimal(info);
                mTvDiscountPrice.setText(String.format("可抵扣金额：%s元", info));
                lastMoney = freight.subtract(discountCouponMoney);
                mTvPredictMoney.setText(String.format("%s元", lastMoney));
            }
        });
    }

    private OptionsPickerView<TimeBean> pvOptions;
    private List<TimeBean> list1;
    private List<List<TimeBean>> list2;
    private List<List<List<TimeBean>>> list3;

    private void getTimeData() {
        list1 = new ArrayList<>();
        list2 = new ArrayList<>();
        list3 = new ArrayList<>();

        long timeMillis = System.currentTimeMillis();
        int day = 86400000;
        list1.add(new TimeBean("今天", DateUtils.getYearMonthDay(timeMillis), 1));
        list1.add(new TimeBean("明天", DateUtils.getYearMonthDay(timeMillis + day), 1));
        list1.add(new TimeBean("后天", DateUtils.getYearMonthDay(timeMillis + (day * 2)), 1));

        final Calendar mCalendar = Calendar.getInstance();
        int mHour = mCalendar.get(Calendar.HOUR_OF_DAY);
        for (int i = 0; i < list1.size(); i++) {
            List<TimeBean> data = new ArrayList<>();
            for (int j = 0; j < 24; j++) {
                if (j <= mHour && i == 0) {
                    continue;
                }
                if (j < 10) {
                    data.add(new TimeBean(String.format("0%s", j), 2));
                } else {
                    data.add(new TimeBean(String.format("%s", j), 2));
                }
            }
            list2.add(data);
        }

        for (int i = 0; i < list1.size(); i++) {
            List<List<TimeBean>> data2 = new ArrayList<>();
            for (int j = 0; j < list2.get(i).size(); j++) {
                List<TimeBean> data = new ArrayList<>();
                for (int k = 0; k < 6; k++) {
                    if (k == 0) {
                        data.add(new TimeBean("00", 3));
                    } else {
                        data.add(new TimeBean(String.format("%s", k * 10), 3));
                    }
                }
                data2.add(data);
            }
            list3.add(data2);
        }
    }

    private void setShipAddress() {
        mTvDepartureAddress.setVisibility(View.VISIBLE);
        mTvDepartureAddress.setText(shipAddress.getAddress());
        mTvDepartureInfo.setText(String.format("%s %s", shipAddress.getTruename(),
                MyUtils.phoneHide(shipAddress.getMobile())));
    }

    private void setShippingAddress() {
        mTvDeliveryAddress.setVisibility(View.VISIBLE);
        mTvDeliveryAddress.setText(shippingAddress.getAddress());
        mTvDeliveryInfo.setText(String.format("%s %s", shippingAddress.getTruename(),
                MyUtils.phoneHide(shippingAddress.getMobile())));
    }

    private void confirm() {
        if (goodTypeDialog == null || !goodTypeDialog.isPerfect()) {
            ToastUtil.show("请完善货物类型");
            return;
        }
        if (packagingDialog == null || !packagingDialog.isPerfect()) {
            ToastUtil.show("请完善包装类型");
            return;
        }
        if (!mCbAgreement.isChecked()) {
            ToastUtil.show("请勾选货物运输协议");
            return;
        }
        Map<String, String> map = new ArrayMap<>();
        map.put("order_type", orderType);
        map.put("pickup_address_id", String.valueOf(shipAddress.getId()));
        map.put("receive_address_id", String.valueOf(shippingAddress.getId()));
        map.put("is_invoice", mRbBilling.isChecked() ? "1" : "0");
        map.put("goods_name", goodTypeDialog.getGoodType());
        map.put("goods_number", String.valueOf(goodTypeDialog.getCount()));
        map.put("goods_weight", String.valueOf(goodTypeDialog.getWeight()));
        map.put("goods_volume", String.valueOf(goodTypeDialog.getVolume()));
        map.put("pack_name", packagingDialog.getPackType());
        map.put("pack_is_special", packagingDialog.isSpecial());
        map.put("pack_imgs", packagingDialog.getImages());
        map.put("pack_long", packagingDialog.sLength());
        map.put("pack_width", packagingDialog.sWidth());
        map.put("pack_height", packagingDialog.sTall());
        map.put("jiaohuo_type", mRbZisongzhuanxian.isChecked() ? "1" : "2");
        map.put("peisong_type", mSonghuoshangmeng.isChecked() ? "1" : "2");
        if (orderType.equals("1")) {
            map.put("logistics_id", companyInfo.getLogistics_id());
            map.put("outlets_id", outlets_id);
        }
        map.put("receipt_type", receipt_type);
        map.put("deliver_type", String.valueOf(index + 1));
        map.put("order_price", String.valueOf(modeList.get(index).getPrice()));
        map.put("remark", mEtRemark.getText().toString());
        map.put("pay_method", pay_method);
        map.put("is_yuyue", TextUtils.isEmpty(appointmentTime) ? "0" : "1");
        if (!TextUtils.isEmpty(uploadTime)) {
            map.put("yuyue_time", uploadTime + ":00");
        }
        if (mRbDiscountCoupon.isChecked() && !TextUtils.isEmpty(coupon_id) && pay_method.equals("1") && index != 2) {
            map.put("coupon_id", coupon_id);
        }
        if (mRbRedPacket.isChecked() && redEnvelopePrice.compareTo(new BigDecimal("0")) > 0 && pay_method.equals("1") && index != 2) {
            map.put("redpack", String.valueOf(redEnvelopePrice));
        }
        loadingPopupShow();
        networkRequest(netApi.create_order(map), this, 666);
    }


    @SuppressLint("NotifyDataSetChanged")
    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 666) {
            loadingPopupDismiss();
            OrderCreationSuccess priceBean = new Gson().fromJson(json, OrderCreationSuccess.class);
            if (priceBean.isStatus()) {
                startActivity(new Intent(mActivity, PayDeskActivity.class)
                        .putExtra("pay_sn", priceBean.getData().getPay_sn())
                        .putExtra("pay_method",pay_method)
                        .putExtra("deliver_sn", priceBean.getData().getDeliver_sn())
                        .putExtra("money", String.valueOf(lastMoney)));
                finish();
            } else {
                ToastUtil.show(priceBean.getMsg());
            }
        } else if (requestCode == 9527) {
            bean = new Gson().fromJson(json, AddressList.class);
        } else if (requestCode == 888) {
            //获取价格信息
            PlatformPriceBean priceBean = new Gson().fromJson(json, PlatformPriceBean.class);
            if (priceBean.isStatus()) {
                int generalDayMax = priceBean.getData().getLine_info().getGeneral_day_max();
                int generalDayMin = priceBean.getData().getLine_info().getGeneral_day_min();
                String putongPrice = priceBean.getData().getPutong_price();

                int fastDayMax = priceBean.getData().getLine_info().getFast_day_max();
                int fastDayMin = priceBean.getData().getLine_info().getFast_day_min();
                String fastPrice = priceBean.getData().getFast_price();
                deliveryExpense = priceBean.getData().getLine_info().getSelf_price();
                pickUpCharge = priceBean.getData().getLine_info().getDispatch_price();
                if (modeList.size() == 0) {
                    LogisticsMode logisticsMode = new LogisticsMode(generalDayMax, generalDayMin, putongPrice, 1);
                    LogisticsMode logisticsMode2 = new LogisticsMode(fastDayMax, fastDayMin, fastPrice, 2);
                    logisticsMode.setCheck(true);
                    modeList.add(logisticsMode);
                    modeList.add(logisticsMode2);
                } else {
                    LogisticsMode logisticsMode = modeList.get(0);
                    logisticsMode.setMaximumDays(generalDayMax);
                    logisticsMode.setMinimumDays(generalDayMin);
                    logisticsMode.setPrice(putongPrice);
                    LogisticsMode logisticsMode2 = modeList.get(1);
                    logisticsMode2.setMaximumDays(fastDayMax);
                    logisticsMode2.setMinimumDays(fastDayMin);
                    logisticsMode2.setPrice(fastPrice);
                }
                freight = new BigDecimal(modeList.get(index).getPrice());
                if (mRbDiscountCoupon.isChecked()) {
                    lastMoney = freight.subtract(discountCouponMoney);
                } else {
                    lastMoney = freight.subtract(redEnvelopePrice);
                }
                mTvPredictMoney.setText(String.format("%s元", lastMoney));
                if (mode.equals("1")) {
                    if (modeList.size() == 2) {
                        modeList.add(new LogisticsMode(3));
                    }
                    logisticsModeAdapter.notifyDataSetChanged();
                } else {
                    if (modeList.size() > 2) {
                        modeList.remove(2);
                    }
                    logisticsModeAdapter.notifyDataSetChanged();
                }
            }
            getDiscounts();
        } else if (requestCode == 999) {
            OutletsData outletsData = new Gson().fromJson(json, OutletsData.class);
            if (outletsData.isStatus()) {
                outletsList = outletsData.getData().getList();
                if (outletsList.size() == 1) {
                    outlets_id = String.valueOf(outletsList.get(0).getOutlets_id());
                    mTvWebsite.setText(outletsList.get(0).getOutlets_name());
                }
                outletsDialog.setList(outletsList);
                platformPrice();
            }
        } else if (requestCode == 9528) {
            OrderDetailsBean detailsBean = new Gson().fromJson(json, OrderDetailsBean.class);
            if (detailsBean.isStatus()) {
                OrderDetailsBean.DataDTO.OrderInfoDTO data = detailsBean.getData().getOrder_info();
                appointmentTime = data.getYuyue_time() > 0 ? DateUtils.getTime2(data.getYuyue_time()) : "";
                shipAddress = new AddressInfo(data.getPickup_city(), data.getPickup_truename(),
                        data.getPickup_mobile(), data.getPickup_address(), data.getPickup_address_id());
                shippingAddress = new AddressInfo(data.getReceive_city(), data.getReceive_truename(),
                        data.getReceive_mobile(), data.getReceive_address(), data.getReceive_address_id());
                orderType = String.valueOf(data.getOrder_type());
                mTvGoodType.setText(String.format("%s、%s件、%st、%sm³", data.getGoods_name(),
                        data.getGoods_number(), data.getGoods_weight(), data.getGoods_volume()));
                mTvPackaging.setText(data.getPack_name());
                goodTypeDialog = new GoodTypeDialog(mActivity);
                goodTypeDialog.setGoodType(data.getGoods_name());
                goodTypeDialog.setCount(data.getGoods_number());
                goodTypeDialog.setWeight(Float.parseFloat(data.getGoods_weight()));
                goodTypeDialog.setVolume(Float.parseFloat(data.getGoods_volume()));
                goodTypeDialog.setPerfect(true);
                if (goodTypeDialog.getWeight() >= 3 || goodTypeDialog.getVolume() >= 9) {
                    mode = "1";
                } else {
                    mode = "2";
                }
                packagingDialog = new PackagingDialog(mActivity);
                packagingDialog.setPackType(data.getPack_name());
                packagingDialog.isSpecial = data.getPack_is_special().equals("1");
                packagingDialog.images = data.getPack_imgs();
                packagingDialog.sLength = data.getPack_long();
                packagingDialog.sWidth = data.getPack_width();
                packagingDialog.sTall = data.getPack_height();
                packagingDialog.setPerfect(true);

                if (data.getReceipt_type() == 1) {
                    mRbDispenseWith.setChecked(true);
                } else if (data.getReceipt_type() == 2) {
                    mRbReceipt.setChecked(true);
                } else {
                    mRbAcknowledgement.setChecked(true);
                }
                mEtRemark.setText(data.getRemark());
                if (data.getJiaohuo_type() == 1) {
                    mRbZisongzhuanxian.setChecked(true);
                } else {
                    mRbShangmengtihuo.setChecked(true);
                }
                if (data.getPeisong_type() == 1) {
                    mSonghuoshangmeng.setChecked(true);
                } else {
                    mRbZiti.setChecked(true);
                }
                initialization();
                platformPrice();
            }
        } else if (requestCode == 369) {
            couponSearchBean = new Gson().fromJson(json, CouponSearchBean.class);
            if (couponSearchBean.getCode().equals("1") && !mRbRedPacket.isChecked()) {
                mTvDiscountPrice.setText(String.format("你有%s张可用的优惠券", couponSearchBean.getData().getList().size()));
            }
        } else if (requestCode == 366) {
            AdvancePayment baseBean = new Gson().fromJson(json, AdvancePayment.class);
            if (baseBean.isStatus()) {
                redEnvelopePrice = new BigDecimal(baseBean.getData().getRedpack());
                if (mRbRedPacket.isChecked()) {
                    lastMoney = freight.subtract(redEnvelopePrice);
                    mTvPredictMoney.setText(String.format("%s元", lastMoney));
                }
            }
        }
    }


    private CouponSearchBean couponSearchBean;
    Map<String, Object> couponMap = new ArrayMap<>();

    private void getDiscounts() {
        couponMap.put("order_type", orderType);
        couponMap.put("limit", "100");
        couponMap.put("page", 1);
        if (companyInfo != null) {
            couponMap.put("logistics_id", companyInfo.getLogistics_id());
        }
        couponMap.put("money", freight);
        networkRequest(netApi.myCouponList(couponMap), this, 369);
        mLlLogisticsMode.setVisibility(View.VISIBLE);
        mLlSelectOffer.setVisibility(View.VISIBLE);
        mLlPreferentialPrice.setVisibility(View.VISIBLE);
        mLlPreferentialPrice.setOnClickListener(this);
        networkRequest(netApi.getRedpackInfo(freight.toString()), this, 366);
    }

    @Override
    public void onFailure(int requestCode) {
        loadingPopupDismiss();
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
//        if (i == R.id.rb_ziti) {
//            mLlSelfPickingDot.setVisibility(View.VISIBLE);
//        } else if (i == R.id.songhuoshangmeng) {
//            mLlSelfPickingDot.setVisibility(View.GONE);
//        }
        platformPrice();
    }
}